package com.cn.zkc3;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenyuncong on 2019/4/1.
 */
public class TastAssist {
    static final String connectString = "127.0.0.1:2181";
    private static final Map<String,Tast> map = new HashMap<>();
    public static void main(String[] args) throws InterruptedException {

        ZkClient zkClient=new ZkClient(new ZkConnection(connectString,10000));
        String masterNode="/task-assist";
        String checkNode=masterNode+"/check-node";
        //监控主节或者子 点添加或者删除
        zkClient.subscribeChildChanges(masterNode, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChild) throws Exception {
                System.out.println("--------------handleChildChange---------------");
                System.out.println("parentPath=" + parentPath);
                System.out.println("currentChild=" + currentChild);
            }

        });

        //监控主节 修改数据，和删除(subscribeChildChanges先运行然后再到subscribeDataChanges监听)
        zkClient.subscribeDataChanges(masterNode, new IZkDataListener() {
            //主节点数据修改
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println("修改节点 path=" + path + ", value=" + data);
            }
            //主节点删除
            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println("删除的节点 path" + path);
            }
        });

        zkClient.subscribeDataChanges(checkNode, new IZkDataListener() {
            //主节点数据修改
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println("check节点 path=" + path + ", value=" + data);
                Tast o = zkClient.readData(data.toString());
                map.put(o.getNodeName(),o);
            }
            //主节点删除
            @Override
            public void handleDataDeleted(String path) throws Exception {
//                System.out.println("删除的节点 path" + path);
            }
        });

        //判断主节点是否存在
        boolean bool = zkClient.exists(masterNode);
        //不存在就创建
        if(!bool){
            zkClient.createPersistent(masterNode,true);
        }
        boolean checkBool = zkClient.exists(checkNode);
        if(!checkBool){
            zkClient.createPersistent(checkNode,null);
        }

        while (true){
            Thread.sleep(100);
        }

    }
}
